#!/bin/bash
copydirectory(){
    pcount=$#
    if [ $pcount -lt 3 ];then
        echo "Usage:cpdir src dst pattern"
        exit
    fi
    pwd_dir=`pwd`
    pary=$@
    incary=${pary[@]:3}
    copydir(){
        cd $1
        for inc in $incary;do
            iary=`ls $inc 2>/dev/null`
            for i in $iary;do
                if [ -f $i ];then
                    cp $i $2
                fi
            done
        done
        for i in $(ls);do
            dir="$1/$i"
            if [ -d $dir ];then
                if [ ! -d "$2/$i" ];then
                    mkdir $2/$i 2>/dev/null
                fi 
                copydir $dir $2/$i
            fi
        done
    }
    #initial.
    src=$1
    dst=$2
    if [ ! -d $2 ];then
        echo "$2 directory is not exist!"
        exit 1
    fi
    tmp=${src:${#src}-1}
    if [ "$tmp" = "/" ];then
        copydir $src $dst
    else 
        leaf=${src##*/}
        if [ ! -d "$dst/$leaf" ];then
            mkdir $dst/$leaf
        fi
        copydir $src $dst/$leaf
    fi
}
copydirectory $@